package cn.com.utt.unms.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;

import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.TableInput;
import cn.com.utt.common.vo.TableOutput;
import cn.com.utt.unms.mapper.AccountConfigMapper;
import cn.com.utt.unms.pojo.AccountConfig;
import cn.com.utt.unms.service.AccountConfigService;
import jxl.CellView;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

@Service("accountConfigService")
public class AccountConfigServiceImpl implements AccountConfigService {
	@Autowired
	private AccountConfigMapper accountConfigMapper;
	@Value("${tempPath}")
	private String temp;

	@Override
	public TableOutput<AccountConfig> queryAccounConfigList(TableInput input, Long userId) {
		Map<String, Object> conditions = new HashMap<>();
		conditions.put("searchs", input.getSearch());
		conditions.put("userId", userId);
		if (input.getOrder() != null) {
			conditions.put("orderColumn", input.getOrder().getColumn());
			conditions.put("orderDirection", input.getOrder().getDir());
		}
		conditions.put("start", input.getStart());
		conditions.put("rows", input.getRows());
		int total = accountConfigMapper.countByCondition(conditions);
		List<AccountConfig> list = accountConfigMapper.queryByCondition(conditions);
		TableOutput<AccountConfig> output = new TableOutput<>();
		output.setList(list);
		output.setRows(input.getRows());
		output.setStart(input.getStart());
		output.setTotal(total);
		return output;
	}

	@Override
	public RestResult addAccountConfig(AccountConfig accountConfig, Byte type, Long userId) {
		RestResult result = new RestResult();
		System.out.println("type: " + type);
		System.out.println("accountConfig: " + JSON.toJSONString(accountConfig));
		if (type == (byte) 0) {// 新增
			accountConfig.setUserId(userId);
			accountConfigMapper.addAccountConfig(accountConfig);
			result.setErrorMsg("新建成功");
		} else {
			accountConfigMapper.editAccountConfig(accountConfig);
			result.setErrorMsg("修改成功");
		}
		return result;
	}

	@Override
	public RestResult delAccountConfig(List<Long> ids, Long userId) {
		RestResult res = new RestResult();
		accountConfigMapper.delAccountConfig(ids);
		res.setErrorMsg("删除成功");
		return res;
	}

	@Override
	public RestResult exportAccountConfig(Long userId) {
		RestResult res=new RestResult();
		List<AccountConfig> list = accountConfigMapper.queryByUserId(userId);
		try {
			Date date = new Date();
			DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String fileName = df.format(date) + "-account.xls";
			File file = new File(temp + fileName);
			if (file.exists() == false) {
				file.createNewFile();
			}
			WritableWorkbook wwb = Workbook.createWorkbook(file);
			// 创建工作表
			WritableSheet ws = wwb.createSheet("account", 0);

			WritableCellFormat wcfF = new WritableCellFormat(NumberFormats.TEXT); // 定义一个单元格样式
			CellView cv = new CellView(); // 定义一个列显示样式
			cv.setFormat(wcfF);// 把定义的单元格格式初始化进去
			cv.setSize(2650);// 设置列宽度（不设置的话是0，不会显示）
			ws.setColumnView(0, cv);// 设置工作表中第n列的样式
			ws.setColumnView(1, cv);// 设置工作表中第n列的样式
			ws.setColumnView(2, cv);// 设置工作表中第n列的样式
			ws.setColumnView(3, cv);// 设置工作表中第n列的样式
			ws.setColumnView(4, cv);// 设置工作表中第n列的样式
			ws.setColumnView(5, cv);// 设置工作表中第n列的样式

			// 要插入到的Excel表格的行号，默认从0开始
			Label labelName = new Label(0, 0, "账号");// 表示第
			Label labelPw = new Label(1, 0, "密码");
			Label labelCreate = new Label(2, 0, "创建时间");
			Label labelStart = new Label(3, 0, "开始时间");
			Label labelEnd = new Label(4, 0, "结束时间");
			Label labelOcuurs = new Label(5, 0, "并发数");
			Label labelRemark = new Label(6, 0, "备注");

			ws.addCell(labelName);
			ws.addCell(labelPw);
			ws.addCell(labelCreate);
			ws.addCell(labelStart);
			ws.addCell(labelEnd);
			ws.addCell(labelOcuurs);
			ws.addCell(labelRemark);
			System.out.println("size:" + list.size());
			for (int i = 0; i < list.size(); i++) {
				AccountConfig account = list.get(i);
				String createTime;
				if (account.getCreateTime() != null) {
					createTime = account.getCreateTime().toString();
					createTime = createTime.substring(0,
							createTime.length() - 2);
				} else {
					createTime = "";
				}
				String startTime;
				if (account.getStartTime() != null) {
					startTime = account.getStartTime().toString();
					startTime = startTime.substring(0, startTime.length() - 2);
				} else {
					startTime = " ";
				}
				String endTime;
				if (account.getEndTime() != null) {
					endTime = account.getEndTime().toString();
					endTime = endTime.substring(0, endTime.length() - 2);
				} else {
					endTime = " ";
				}
				Label name = new Label(0, i + 1, account.getUsername());// 表示第
				Label pw = new Label(1, i + 1, account.getPassword());
				Label create = new Label(2, i + 1, createTime);
				Label start = new Label(3, i + 1, startTime);
				Label end = new Label(4, i + 1, endTime);
				Label occurs = new Label(5, i + 1, account.getMaxOccurs().toString());
				Label remark = new Label(6, i + 1, account.getRemark());

				ws.addCell(name);
				ws.addCell(pw);
				ws.addCell(create);
				ws.addCell(start);
				ws.addCell(end);
				ws.addCell(occurs);
				ws.addCell(remark);
			}

			// 写进文档
			wwb.write();
			// 关闭Excel工作簿对象
			wwb.close();
			InputStream fileInputStream = new FileInputStream(file);
			res.setErrorMsg("导出excel成功");
		} catch (Exception e) {
			e.printStackTrace();
			res.setErrorCode(1);
			res.setErrorMsg("导出excel失败");
		}

		return null;
	}

	@Override
	public RestResult importAccountConfig(File file, Long userId) {
		RestResult result=new RestResult();
		String fileName = file.getName();
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
		org.apache.poi.ss.usermodel.Workbook xssfWorkbook = null;
		InputStream stream = null;
		try {
			stream = new FileInputStream(file);
			if (fileType.equals("xls")) {
				xssfWorkbook = new HSSFWorkbook(stream);
			} else if (fileType.equals("xlsx")) {
				xssfWorkbook = new XSSFWorkbook(stream);
			} else {
				if (stream != null) {
					stream.close();
				}
				result.setErrorCode(-1);
				result.setErrorMsg("您输入的excel格式不正确");
				return result;
			}
		} catch (Exception e) {
			result.setErrorCode(-1);
			result.setErrorMsg("通信异常,请稍后再试");
			return result;
		}
		// Read the Sheet
		org.apache.poi.ss.usermodel.Sheet Sheet = xssfWorkbook.getSheetAt(0);
		String errorMsg = "";
		int errorCode = 0;
		boolean unsafe = true;
		boolean snNull = false;
		List<AccountConfig> list=new ArrayList<>();
		for (int rowNum = 1; rowNum <= Sheet.getLastRowNum(); rowNum++) {
			Row row = Sheet.getRow(rowNum);
			if (row != null) {
				// 获取每一行
				int max = row.getLastCellNum();
				if (max == 0 || (getValue(row.getCell(0)).trim().equals("")
						&& getValue(row.getCell(1)).trim().equals("") && getValue(row.getCell(2)).trim().equals(""))) {
					continue;
				}
				if (max > 7) {
					result.setErrorCode(-1); 
					result.setErrorMsg("文件格式不正确");
					return result;
				}
				AccountConfig accountConfig = new AccountConfig();
				accountConfig.setUserId(userId);
				accountConfig.setUsername(getValue(row.getCell(0)).trim());
				accountConfig.setPassword(getValue(row.getCell(1)).trim());
//				accountConfig.setCreateTime(getValue(row.getCell(2)).trim());
//				accountConfig.setStartTime(getValue(row.getCell(3)).trim());
//				accountConfig.setEndTime(getValue(row.getCell(4)).trim());
				accountConfig.setMaxOccurs(Integer.parseInt(getValue(row.getCell(5)).trim()));
				accountConfig.setRemark(getValue(row.getCell(6)).trim());
				list.add(accountConfig);
			}
			System.out.println("list:  "+JSON.toJSONString(list));
			accountConfigMapper.batchSave(list);//批量保存
		}
		result.setErrorCode(errorCode);
		result.setErrorMsg(errorMsg);
		return result;
	}
	private String getValue(Cell cell) {
		if (cell == null) {
			return "";
		}
		cell.setCellType(Cell.CELL_TYPE_STRING);
		return cell.getStringCellValue().trim();
	}
}
